package pt.iscte.pcd.avioes;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.util.Observable;
import java.util.Observer;

import javax.swing.ImageIcon;
import javax.swing.JComponent;

public class Board extends JComponent implements Observer {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private int nLines;
	private int nCol;
	private int selected = -1;
	private ImageIcon planeImage = null;
	private int x;
	private int y;

	public Board(int nLines, int nCol) {
		super();
		this.nLines = nLines;
		this.nCol = nCol;
		planeImage = new ImageIcon("plane.png");
	}

	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		int dx = getWidth() / (nCol);
		int dy = getHeight() / (nLines);
		for (int i = 1; i < nLines; i++) {
			g.drawLine(0, i * dy, getWidth(), i * dy);
		}
		for (int i = 1; i < nCol; i++) {
			g.drawLine(i * dx, 0, i * dx, getHeight());
		}
		
		g.drawImage(planeImage.getImage(), x, y, null);
//		for (int i = 0; i < nCol * nLines; i++) {
//			String label = "" + i;
//			int w = g.getFontMetrics().stringWidth(label) / 2;
//			int h = g.getFontMetrics().getDescent();
//			int x = (int) ((i % nCol + .5) * dx - w);
//			int y = (int) ((i / nCol + .5) * dy + h);
//			g.drawString(label, x, y);
//		}
//		if (selected >= 0) {
//			g.setColor(Color.DARK_GRAY);
//			g.fillRect((int) ((selected % nCol) * dx),
//					(int) ((selected / nCol) * dy), dx, dy);
//			g.setColor(Color.red);
//			String label = selected + "";
//			int w = g.getFontMetrics().stringWidth(label) / 2;
//			int h = g.getFontMetrics().getDescent();
//			int x = (int) ((selected % nCol + .5) * dx - w);
//			int y = (int) ((selected / nCol + .5) * dy + h);
//			g.drawString(label, x, y);
//			g.setColor(Color.black);
//		}
	}

	@Override
	public void update(Observable arg0, Object arg1) {
		int dx = getWidth() / (nCol);
		int dy = getHeight() / (nLines);
		Aviao av = (Aviao)arg0;
		//System.out.println("Updating from " + x + ", " + y);
		x  = av.getX() * dx;
		y = av.getY() * dy;
//		System.out.println("Updating " + av.getX() + ", " + av.getY());
//		System.out.println("Updating " + dx + ", " + dy);
//		System.out.println("Updating to " + x + ", " + y);
		repaint(); // 2
	}

//	public void setSelected(Point point) {
//		int col = (int) (point.getX() / (getWidth() / nCol));
//		int lin = (int) (point.getY() / (getHeight() / nLines));
//		selected = col + lin * nCol;
//		System.out.println(selected + ": col= " + col + ", lin= " + lin);
//		repaint();
//	}
}
